<template>
  <div class="app-container">
    <u-page-config
      :filter-array="filterArray"
      v-model="filter"
      :actionBtn="actionBtn"
      label-width="100px"
      :getList="getList"
      :tableData="tableData"
      :tableColumn="tableColumn"
      :total="total"
      :loading="loading"
      showSelection
      @handleSelectionChange="handleSelectionChange"
      @addRow="addRow"
      @removeRow="removeRow"
      @editRow="editRow"
      @resolveWorkOrder="resolveWorkOrder"
      @rowDetail="rowDetail"
      @export="handleExport"
    >

      <template #orderStatus="{ row, item }">
        <el-tag size="small" effect="dark" :type="isTagType(row.orderStatus)">
          {{ getDictLabel(orderStatusOptions, row.orderStatus) }}
        </el-tag>
      </template>
      <template #operationUserName="{ row, item }">
        {{ row.orderStatus !== 0 ? row.operationUserName : '' }}
      </template>
    </u-page-config>

    <add-work-order-dialog v-model="visible" :mode="mode" :originForm="form" @getList="getList"/>

    <select-device-dialog v-model="selectDeviceDialogVisible" @select="handleSelectDevice"/>

    <el-dialog title="解决工单" :visible.sync="resolveWorkOrderFormVisible" width="650px" :close-on-click-modal="false">
      <u-form ref="uFormRef" label-width='134px' v-model="form" :defaultForm="defaultForm"
              :formArray="resolveWorkOrderFormArray" @submit="resolveWorkOrderSubmit"
              @close="resolveWorkOrderFormVisible = false" mode="form">
        <template #deviceId="scope">
          <div class="form-item-wrap">
            <el-input placeholder="请输入设备ID或者点击选择设备按钮" v-model="form[scope.row.key]" style="flex: 1;margin-right: 10px;"
                      clearable @change="checkDeviceIdValid">
            </el-input>
            <el-button icon="el-icon-search" type="primary" @click="showSelectDeviceView">选择设备</el-button>
          </div>
        </template>

        <template #image="scope">
          <u-file-upload :value="form.image" :limit="3" :fileSize="10" @input="imageUploadChange"/>
        </template>

        <template v-if="form.orderStatus" #orderStatus="scope">
          <el-tag size="small" effect="dark" :type="isTagType(form.orderStatus)">
            {{ getDictLabel(orderStatusOptions, form.orderStatus) }}
          </el-tag>
        </template>
      </u-form>
    </el-dialog>
  </div>
</template>

<script>
import UPageConfig from '@/components/uPageConfig/index'
import UForm from '@/components/uForm'
import table from "@/mixin/uTable";
import AddWorkOrderDialog from './components/addWorkOrderDialog'
import {
  getWorkOrderList,
  addWorkOrder,
  updateWorkOrder,
  WorkOrderDetail,
  deleteWorkOrder
} from '@/api/operationAndMonitoring/workOrder'
import {listManager} from "@/api/device/placeManager";
import SelectDeviceDialog from "./components/SelectDeviceDialog";

export default {
  name: "WorkerOrder",
  mixins: [table],
  components: {UPageConfig, UForm, SelectDeviceDialog, AddWorkOrderDialog},
  computed: {
    // 运维人员下拉框数据
    operationUserOptions() {
      return this.$store.state.device.operationUserOptions || []
    },
  },
  data() {
    return {
      // 工单状态（0未处理、1处理完成、2不需要处理
      orderStatusOptions: [
        {label: '未处理', value: 0},
        {label: '处理完成', value: 1},
        {label: '不需要处理', value: 2},
      ],
      filterArray: [
        {label: "设备部署名称", key: "deploymentName", type: "input"},
        {label: "工单状态", key: "orderStatus", type: "select", options: []},
        {label: "所属运维人员", key: "operationUserCode", type: "select", options: []},
        // {label: "创建时间", key: "daterange", type: "daterange", noRequestParams: true},
      ],
      tableColumn: [
        {label: "工单ID", prop: "id"},
        {label: "设备ID", prop: "deviceId"},
        {label: "设备部署名称", prop: "deploymentName"},
        {label: "异常内容", prop: "message"},
        {label: "照片", prop: "image", type: 'image'},
        {label: "生成时间", prop: "createTime", type: 'time'},
        {label: "处理状态", prop: "orderStatus", type: 'slot', slot: 'orderStatus'},
        {label: "处理人", prop: "operationUserName", type: 'slot', slot: 'operationUserName'},
        {
          label: "操作", type: "btn", attr: {width: 180}, btnArr: [
            {icon: "el-icon-view", text: "详细", emit: "rowDetail"},
            {
              icon: "el-icon-edit",
              text: "处理工单",
              emit: "resolveWorkOrder",
              permissions: 'operationAndMonitoring:workOrder:resolve',
              disabledRule: (row) => row.orderStatus !== 0
            },
            {
              icon: "el-icon-edit-outline",
              text: "修改",
              emit: "editRow",
              permissions: 'operationAndMonitoring:workOrder:edit',
              disabledRule: (row) => row.orderStatus === 1
            },
            {
              icon: "el-icon-delete",
              text: "删除",
              emit: "removeRow",
              permissions: 'operationAndMonitoring:workOrder:remove'
            },
          ]
        }
      ],
      actionBtn: [
        {
          type: 'primary',
          text: '创建工单',
          icon: 'el-icon-plus',
          emit: 'addRow',
          permissions: 'operationAndMonitoring:workOrder:add'
        },
        /*{
          type: 'success',
          text: '修改',
          icon: 'el-icon-edit',
          emit: 'editRow',
          permissions: 'operationAndMonitoring:workOrder:edit',
          disabledRule: () => this.ids.length !== 1
        },*/
        {
          type: 'danger',
          text: '删除',
          icon: 'el-icon-delete',
          emit: 'removeRow',
          permissions: 'operationAndMonitoring:workOrder:remove',
          disabledRule: () => this.ids.length === 0
        },
        {
          type: 'warning',
          text: '导出',
          icon: 'el-icon-download',
          emit: 'export',
          permissions: 'operationAndMonitoring:workOrder:export'
        },
      ],
      // 表单默认必填参数 重置表单时需要用到
      defaultForm: {
        deviceId: '',
        deploymentName: '',
        deploymentCode: '',
        operationUserCode: '',
        message: '',
        image: '',
        reportName: '',
        reportPhone: '',
      },
      // 选择设备弹窗
      selectDeviceDialogVisible: false,
      resolveWorkOrderFormVisible: false,
      resolveWorkOrderFormArray: [
        {
          label: "处理状态：", key: "orderStatus", col: 24, type: "select",
          rule: {required: true, message: '处理状态不能为空！', trigger: 'blur'},
        },
        {
          label: "原因及处理结果：", key: "dealResult", col: 24, type: "textarea",
          rule: {required: true, message: '原因及处理结果不能为空！', trigger: 'blur'},
        },
        {
          label: "处理人：", key: "operationUserCode", col: 24, type: "select", options: [],
          rule: {required: true, message: '处理人不能为空！', trigger: 'blur'},
        },
        {
          label: "处理时间：", key: "dealTime", col: 24, type: "datetime",
          attr: {defaultValue: Date.now()},
          rule: {required: true, message: '处理时间不能为空！', trigger: 'blur'},
        },
      ]
    };
  },
  methods: {
    // tag样式
    isTagType(value) {
      switch (value) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'info'
      }
    },
    // 弹出选择设备弹窗
    showSelectDeviceView() {
      // 设置处理时间选择器默认为当前时间
      this.resolveWorkOrderFormArray[3].attr.defaultValue = Date.now();
      this.selectDeviceDialogVisible = true
    },
    // 提交解决工单
    resolveWorkOrderSubmit(closeLoading) {
      const operationUserName = this.operationUserOptions.find(item => item.value === this.form.operationUserCode)?.label || undefined
      const params = {
        id: this.form.id,
        deviceId: this.form.deviceId,
        orderStatus: this.form.orderStatus,
        dealResult: this.form.dealResult,
        operationUserCode: this.form.operationUserCode,
        operationUserName,
        dealTime: this.form.dealTime,
      }
      updateWorkOrder(params).then(response => {
        closeLoading()
        this.$modal.msgSuccess("提交成功！");
        this.resolveWorkOrderFormVisible = false;
        this.getList();
      })
    },
    // 处理工单
    resolveWorkOrder(row) {
      this.form = JSON.parse(JSON.stringify(row))
      // 清空当前状态，让用户自己选
      this.form.orderStatus = null;
      this.resolveWorkOrderFormVisible = true;
    },
    /** 查询该ID在设备部署管理列表是否存在*/
    checkDeviceIdValid(id) {
      this.checkIdLoading = true;
      this.isValidDeviceId = false;
      // 请求参数
      const params = {
        deviceId: this.form.deviceId
      };
      listManager(params).then(response => {
          const list = response.rows;
          if (list.length) {
            this.isValidDeviceId = true;
            this.form.deploymentName = list[0].deploymentName
            this.form.deploymentCode = list[0].deploymentCode
          } else {
            this.$modal.confirmAlert('该设备ID不存在已部署设备列表，请重新输入！')
          }
          console.log(response, 'listManager')
        }
      ).finally(() => {
        this.checkIdLoading = false;
      })
    },
    // 表单提交接口相关配置
    formSubmitFunConfig() {
      return {
        addFunc: addWorkOrder,
        modifyFunc: updateWorkOrder,
        pk: 'id',
        options: {
          ...this.form
        },
        cbFunc: () => {
          this.visible = false
        }
      }
    },
    // 删除
    removeRow(row) {
      const id = row ? row.id : this.ids;
      this.removeTip(async () => {
        await deleteWorkOrder(id)

      }, row ? '该项数据' : '已勾选项数据')
    },
    // 添加
    addRow() {
      this.mode = 'form';
      this.form = {};
      this.title = "添加工单";
      this.visible = true;
    },
    // 修改
    async editRow(row) {
      this.mode = 'form'
      this.title = "修改工单";
      if (row) { //点击的表格内修改按钮
        this.form = JSON.parse(JSON.stringify(row))
      } else { //点击表格上方修改按钮
        const selectedItem = this.tableData.find(item => this.ids[0] === item.id) || {}
        this.form = JSON.parse(JSON.stringify(selectedItem))
      }
      this.visible = true
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    // 选择设备列表弹窗 选择设备回调
    handleSelectDevice(deviceInfo) {
      this.form.deviceId = deviceInfo.deviceId;
      this.form.deploymentCode = deviceInfo.deploymentCode;
      this.form.deploymentName = deviceInfo.deploymentName;
    },
    // 添加文件上传成功、删除图片时都会被调用
    imageUploadChange(imgUrl) {
      this.form.image = imgUrl
    },
    /** 查询工单列表 */
    getList() {
      this.getInit(getWorkOrderList, {})
    },
    /** 详细按钮操作 */
    rowDetail(row) {
      this.mode = 'text'
      this.title = '详细信息'
      this.form = JSON.parse(JSON.stringify(row))
      this.visible = true
    },
    /** 返回设备部署页面 */
    goBack() {
      this.$router.go(-1);
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      const ids = this.ids;
      const params = this.getListRequestParams();
      this.download(
        "/device/workOrder/export",
        params,
        `工单列表_${currentDate}.xlsx`,
      );
    },
  },
  watch: {
    operationUserOptions: {
      immediate: true,
      handler(newValue) {
        // 设置运维人员选项数据
        try {
          this.filterArray.find(item => item.key === 'operationUserCode').options = newValue;
          this.resolveWorkOrderFormArray.find(item => item.key === 'operationUserCode').options = newValue;
        } catch (e) {
          console.log("找不到对应表单项", e)
        }
      }
    }
  },
  created() {
    try {
      this.filterArray.find(item => item.key === 'orderStatus').options = this.orderStatusOptions;
      this.resolveWorkOrderFormArray.find(item => item.key === 'orderStatus').options = this.orderStatusOptions;
    } catch (e) {
      console.log("找不到对应表单项", e)
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-wrap {
  display: flex;
}
</style>
